import os
from werkzeug.utils import secure_filename
from datetime import datetime
import uuid
from flask import current_app, request

ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def save_image(file, subfolder='images'):
    """保存图片并返回访问URL"""
    if not file:
        return None
        
    if not allowed_file(file.filename):
        raise ValueError(f'Invalid file type. Allowed types are: {", ".join(ALLOWED_EXTENSIONS)}')
        
    # 获取上传目录的绝对路径
    upload_path = os.path.join(current_app.config['UPLOAD_FOLDER'], subfolder)
    
    # 确保上传目录存在
    os.makedirs(upload_path, exist_ok=True)
    
    # 生成安全的文件名
    filename = secure_filename(file.filename)
    # 添加时间戳和UUID避免文件名冲突
    ext = filename.rsplit('.', 1)[1].lower()
    new_filename = f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_{str(uuid.uuid4())[:8]}.{ext}"
    
    # 保存文件
    file_path = os.path.join(upload_path, new_filename)
    file.save(file_path)
    
    # 构建完整的URL
    host_url = request.host_url.rstrip('/')  # 获取主机URL（去掉末尾的斜杠）
    return f"{host_url}/uploads/{subfolder}/{new_filename}" 